package color.koitq.picker.activty;

import static color.koitq.picker.ad.AdConfig.AD_LOG_TAG;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.rxjava.rxlife.RxLife;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.Map;

import butterknife.BindView;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.observers.ResourceObserver;
import rxhttp.wrapper.param.RxHttp;
import color.koitq.picker.BuildConfig;
import color.koitq.picker.MainActivity;
import color.koitq.picker.R;
import color.koitq.picker.ad.AdActivity;
import color.koitq.picker.ad.AdConfig;
import color.koitq.picker.ad.TTAdManagerHolder;
import color.koitq.picker.ad.UIUtils;
import color.koitq.picker.base.BaseActivity;
import color.koitq.picker.entity.AdConfigModel;
import color.koitq.picker.entity.ApiConfig;

public class LauncherActivity extends BaseActivity {

    private int loadCount = 1;

    @BindView(R.id.splash_container)
    FrameLayout mSplashContainer;

    //开屏广告加载超时时间,建议大于3000
    private static final int AD_TIME_OUT = 3500;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_launcher;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void init() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        AdActivity.lastWatchVideo = 0;
        AdActivity.lastShowDialog = 0;
        AdActivity.onlyOneVideo = true;

        if ("1".equals(AdConfig.getAdAppId()) || TextUtils.isEmpty(AdConfig.getSplashCodeId())) {
            queryAdMethod();
        } else {
            initAdConfig();
        }
    }

    private void initUmeng() {
        //初始化组件化基础库, 所有友盟业务SDK都必须调用此初始化接口。
        //建议在宿主App的Application.onCreate函数中调用基础组件库初始化函数。
        UMConfigure.init(this, AdConfig.UmengId, getString(R.string.channel), UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    private void showMain() {
        if (TextUtils.isEmpty(AdConfig.getSplashCodeId())) {
            AdConfig.adDisable = true;
        }
        new Handler().postDelayed(() -> {
            if (!AdConfig.adDisable) {
                initUmeng();
                Log.i(AD_LOG_TAG,"开始初始化");
                if (TTAdSdk.isInitSuccess()) {
                    Log.i(AD_LOG_TAG,"初始化成功1");
                    loadSplashAd();
                } else {
                    TTAdManagerHolder.init(new TTAdSdk.InitCallback() {
                        @Override
                        public void success() {
                            Log.i(AD_LOG_TAG,"初始化成功");
                            loadSplashAd();
                        }

                        @Override
                        public void fail(int i, String s) {
                            Log.i(AD_LOG_TAG,"初始化失败");
                            AdConfig.adDisable = true;
                            goToMainActivity();
                        }
                    });
                }
            } else {
                goToMainActivity();
            }
        }, 500);
    }

    private void queryAdMethod() {
        RxHttp.postForm(ApiConfig.queryConfigByKey)
                .add("key", BuildConfig.APPLICATION_ID)
                .asClass(AdConfigModel.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(new ResourceObserver<AdConfigModel>() {
                    @Override
                    public void onNext(@NonNull AdConfigModel apiModel) {
                        if (apiModel.getCode() == AdConfigModel.SUCCESSCODE) {
                            Map<String, String> adConfigEntity = apiModel.getObj();
                            if (adConfigEntity != null) {
                                AdConfig.setAdAppId(adConfigEntity.get("appName"));
                                AdConfig.setSplashCodeId(adConfigEntity.get("huawei"));
                                AdConfig.setVideoCodeId(adConfigEntity.get("vivo"));
                                AdConfig.setDialogCodeId(adConfigEntity.get("xiaomi"));
                                AdConfig.setBannerCodeId(adConfigEntity.get("oppo"));
                                AdConfig.setFeedCodeId(adConfigEntity.get("three"));

                                String channel = getString(R.string.channel);
                                int closeAd = apiModel.getCloseAd();
                                if (closeAd == -1) {
                                    AdConfig.adDisable = BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)));
                                } else {
                                    if ("huawei".equals(channel) || "vivo".equals(channel)) {
                                        AdConfig.adDisable = apiModel.getCloseAd() == 1;
                                    } else {
                                        AdConfig.adDisable = BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)));
                                    }
                                }

                                AdConfig.vacation = apiModel.getVacation();
                                String status = adConfigEntity.get("status");
                                if ("0".equals(status)) {
                                    AdConfig.vacation = AdConfig.VACATION_WORKING;
                                }

                                /**
                                 * meizu
                                 * 1:直接采用下班模式
                                 * 2:直接采用节假日模式
                                 * */
                                String meizu = adConfigEntity.get("meizu");
                                if ("1".equals(meizu)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK;
                                } else if ("2".equals(meizu)) {
                                    AdConfig.vacation = AdConfig.VACATION_HOLIDAY;
                                }

                                /**
                                 * baidu
                                 * 控制间隔时间（默认间隔时间是2分钟）
                                 * 例如：baidu = 1，代表一分钟；baidu = 2，代表2分钟
                                 * */
                                String baidu = adConfigEntity.get("baidu");
                                if (!TextUtils.isEmpty(baidu)) {
                                    try {
                                        int temp = Integer.parseInt(baidu);
                                        AdActivity.AdDelay = temp * 60 * 1000;
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }

                            } else {
                                AdConfig.adDisable = apiModel.getCloseAd() == 1;
                            }
                        } else {
                            AdConfig.adDisable = apiModel.getCloseAd() == 1;
                        }
                        showMain();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (loadCount > 2) {
                            showMain();
                        } else {
                            loadCount++;
                            queryAdMethod();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initAdConfig() {
        RxHttp.postForm(ApiConfig.queryConfigByKey)
                .add("key", AdConfig.getAdAppId())
                .asClass(AdConfigModel.class)
                .to(RxLife.toMain(this))
                .subscribe(new ResourceObserver<AdConfigModel>() {
                    @Override
                    public void onNext(@NonNull AdConfigModel apiModel) {
                        if (apiModel.getCode() == AdConfigModel.SUCCESSCODE) {
                            Map<String, String> adConfigEntity = apiModel.getObj();
                            if (adConfigEntity != null) {
                                String status = adConfigEntity.get("status");
                                if ("0".equals(status) && BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)))) {
                                    AdConfig.adDisable = true;
                                } else {
                                    String channel = getString(R.string.channel);
                                    int closeAd = apiModel.getCloseAd();
                                    if (closeAd == -1) {
                                        AdConfig.adDisable = BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)));
                                    } else {
                                        if ("huawei".equals(channel) || "vivo".equals(channel)) {
                                            AdConfig.adDisable = apiModel.getCloseAd() == 1;
                                        } else {
                                            AdConfig.adDisable = BuildConfig.VERSION_NAME.equalsIgnoreCase(adConfigEntity.get(getString(R.string.channel)));
                                        }
                                    }
                                }

                                AdConfig.vacation = apiModel.getVacation();
                                if ("0".equals(status)) {
                                    AdConfig.vacation = AdConfig.VACATION_WORKING;
                                }

                                /**
                                 * meizu
                                 * 1:直接采用下班模式
                                 * 2:直接采用节假日模式
                                 * */
                                String meizu = adConfigEntity.get("meizu");
                                if ("1".equals(meizu)) {
                                    AdConfig.vacation = AdConfig.VACATION_OFF_WORK;
                                } else if ("2".equals(meizu)) {
                                    AdConfig.vacation = AdConfig.VACATION_HOLIDAY;
                                }

                                /**
                                 * baidu
                                 * 控制间隔时间（默认间隔时间是2分钟）
                                 * 例如：baidu = 1，代表一分钟；baidu = 2，代表2分钟
                                 * */
                                String baidu = adConfigEntity.get("baidu");
                                if (!TextUtils.isEmpty(baidu)) {
                                    try {
                                        int temp = Integer.parseInt(baidu);
                                        AdActivity.AdDelay = temp * 60 * 1000;
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }

                            } else {
                                AdConfig.adDisable = apiModel.getCloseAd() == 1;
                            }
                        } else {
                            AdConfig.adDisable = apiModel.getCloseAd() == 1;
                        }
                        showMain();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (loadCount > 2) {
                            showMain();
                        } else {
                            loadCount++;
                            initAdConfig();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);

        int splashWidthPx = UIUtils.getScreenWidthInPx(this);
        int splashHeightPx = UIUtils.getScreenHeight(this);

        float splashWidthDp = UIUtils.getScreenWidthDp(this);
        float splashHeightDp = UIUtils.px2dip(this, splashHeightPx);

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(AdConfig.getSplashCodeId())
                .setExpressViewAcceptedSize(splashWidthDp, splashHeightDp) // 单位是dp
                .setImageAcceptedSize(splashWidthPx, splashHeightPx) // 单位是px
                .build();

        TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.CSJSplashAdListener() {

            @Override
            public void onSplashLoadSuccess() {

            }

            @Override
            public void onSplashLoadFail(CSJAdError error) {
                goToMainActivity();
            }

            @Override
            public void onSplashRenderSuccess(CSJSplashAd ad) {
                if (ad == null) {
                    return;
                }
                mSplashContainer.setVisibility(View.VISIBLE);
                ad.showSplashView(mSplashContainer);
                ad.setSplashAdListener(new CSJSplashAd.SplashAdListener() {
                    @Override
                    public void onSplashAdShow(CSJSplashAd ad) {
                        Log.d(AD_LOG_TAG, "onAdShow");
                    }

                    @Override
                    public void onSplashAdClick(CSJSplashAd ad) {
                        Log.d(AD_LOG_TAG, "onAdClicked");
                    }

                    @Override
                    public void onSplashAdClose(CSJSplashAd ad, int closeType) {
                        goToMainActivity();
                    }
                });
            }

            @Override
            public void onSplashRenderFail(CSJSplashAd ad, CSJAdError csjAdError) {
                goToMainActivity();
            }
        }, AD_TIME_OUT);

    }

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
        startActivity(intent);
        if (mSplashContainer != null) {
            mSplashContainer.removeAllViews();
        }
        this.finish();
    }

}